package protocol.transactions;

import java.lang.reflect.Type;
import java.util.List;

import protocol.XoneProtocol;
import protocol.XoneServiceCode;
import protocol.meta.AppInfo;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.netease.http.THttpRequest;
import com.netease.pkgRelated.XoneConsts;

import db.manager.ManagerAppInfo;


public class TransactionGetUserDiscussList extends XoneBaseTransaction {

    private boolean mRefresh;
    private String mUserId;
    private int mCount;
    private long mMaxTime;
    private long mSinceTime;

    public TransactionGetUserDiscussList(boolean refresh, String userId, int count, long maxTime, long sinceTime) {
        super(TRANSACTION_TYPE_GET_USER_DISCUSS_LIST);
        mRefresh = refresh;
        mUserId = userId;
        mSinceTime = sinceTime;
        mCount = count;
        mMaxTime = maxTime;
    }

    @Override
    protected void onXoneTransactionSuccess(int code, Object obj) {
        if (obj instanceof JsonElement) {
            boolean hasMore = false;
            long maxTime = -1;
            try {
                JsonElement array = ((JsonElement)obj).getAsJsonObject().get("list");
                Gson gson = new Gson();
                List<AppInfo> list = null;
                Type collectionType = new TypeToken<List<AppInfo>>(){}.getType();
                list = gson.fromJson(array, collectionType);
                if(list != null && list.size() == XoneConsts.LIST_ITEM_COUNT.ONE_REQUEST_COUNT){
                    hasMore = true;
                    maxTime = list.get(list.size() - 1).getTime();
                }
                if(mRefresh){
                    ManagerAppInfo.delete(ManagerAppInfo.GROUP_USER_DISCUSS_LIST, Long.valueOf(mUserId));
                }
                if (0 < list.size()) {
                    ManagerAppInfo.replaceAppInfo(ManagerAppInfo.GROUP_USER_DISCUSS_LIST, Long.valueOf(mUserId), list);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            Object[] data = new Object[2];
            data[0] = hasMore;
            data[1] = maxTime;
            notifyMessage(XoneServiceCode.TRANSACTION_SUCCESS, data);
        }else{
            notifyError(XoneServiceCode.TRANSACTION_FAIL, null);
        }
    }

    @Override
    public void onTransact() {
        THttpRequest request = XoneProtocol.getInstance().createGetUserDiscussList(mUserId, mCount, mMaxTime, mSinceTime);
        sendRequest(request);
    }
}
